package com.dong.com.love.cach;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;

import android.content.Context;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

/**
 * @desc 本地缓存工具类
 * @author DongHuadong
 *
 */

public class CachUtils {

	//存入缓存
	public static void saveCach(Context context,Object obj,String name){

		Gson gson=new GsonBuilder().create();
		String json = gson.toJson(obj);
		try {
			File file=new File(context.getExternalCacheDir(),name);
			if(!file.exists()){
				file.createNewFile();
			}
			BufferedWriter fw=new BufferedWriter(new FileWriter(file));
			fw.write(json);
			fw.close();		
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	//取出缓存
	public static <T>T getCach(Context context,Class<T> classOfT,String name,int time){

		File file=new File(context.getExternalCacheDir(),name);
		if(!file.exists()){
			return null;
		}

		T obj =null;
		try {
			long lastModified = file.lastModified();
			long currentTimeMillis = System.currentTimeMillis();

			if(currentTimeMillis-lastModified>time){
				return null;
			}

			Gson gson=new GsonBuilder().create();
			StringBuffer buffer = new StringBuffer("");
			BufferedReader fr=new BufferedReader(new FileReader(file));
			String tmp =null;
			while((tmp = fr.readLine())!=null ) {
				buffer.append(tmp);
			}

			fr.close();
			if(!"".equals(buffer.toString())) {
				String json = buffer.toString();			
				obj = gson.fromJson(json, classOfT);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return obj;
	}

	/*
	 * 删除缓存
	 */
	public static void deleteCach(Context context){
		File cacheDir = context.getExternalCacheDir();
		delete(cacheDir);
	}

	
	private static void delete(File file) {
		if(file!=null){
			File[] files = file.listFiles();
			for (int i = 0; i < files.length; i++) {
				if(files[i].isFile())
					files[i].delete();
				if(files[i].isDirectory()){
					Log.i("TAG", files[i].getAbsolutePath());
					delete(files[i]);
				}

			}
		}
	}
	

}
